package com.cn.Dao;

import com.cn.base.BaseDao;
import com.cn.entity.DepInfo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DepDao {
    public List<DepInfo> findAll() throws SQLException {
        Connection connection = BaseDao.getConn();
        try {
            Statement state=connection.createStatement();
            String sql="select * from department";
            ResultSet rs = state.executeQuery(sql);
            List<DepInfo> depInfos = getList(rs);
            connection.close();
            return depInfos;
        }catch (Exception e){
            throw e;
        }
    }
private DepInfo getDep(ResultSet resultSet){
    try {
        DepInfo depInfo = new DepInfo();
        while (resultSet.next()){
            depInfo.setDepartmentid(resultSet.getInt(1));
            depInfo.setDname(resultSet.getString(2));
        }
        return depInfo;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
    private List<DepInfo> getList(ResultSet resultSet){
        try {
            List<DepInfo> depInfos=new ArrayList<>();
            while (resultSet.next()){
                DepInfo depInfo = new DepInfo();
                depInfo.setDepartmentid(resultSet.getInt(1));
                depInfo.setDname(resultSet.getString(2));
                depInfos.add(depInfo);
            }
            return depInfos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public DepInfo findById(Integer departmentid) throws SQLException {
        Connection connection = BaseDao.getConn();
        try {
            Statement state=connection.createStatement();
            String sql="select * from department where DEP_ID='"+departmentid+"'";
            ResultSet rs = state.executeQuery(sql);
            DepInfo depInfo = getDep(rs);
            connection.close();
            return depInfo;
        }catch (Exception e){
            throw e;
        }
    }
}
